package com.alibaba.algo.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Value("${swagger2.enable:false}")
    private Boolean enable;
    private static final String splitor = ";";


    @Bean
    public Docket createCommonRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(commonApiInfo())
                .enable(enable)
                .select()
                .apis(basePackage("com.alibaba.algo.controller"))
                .paths(PathSelectors.any())
                .build().groupName("默认分组");
    }


    @Bean
    public Docket createFeignRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(commonApiInfo())
                .enable(enable)
                .select()
                .apis(basePackage("com.alibaba.algo.apiimpl.feign"))
                .paths(PathSelectors.any())
                .build().groupName("Feign接口");
    }

    private ApiInfo commonApiInfo() {
        return new ApiInfoBuilder().title("用户组件 API")
                .description("API接口文档")
                .version("1.0")
                .build();
    }


    /**
     * 重写basePackage方法，使能够实现多包访问，复制贴上去
     * @author  teavamc
     * @date 2019/1/26
     * @param [basePackage]
     * @return com.google.common.base.Predicate<springfox.documentation.RequestHandler>
     */
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

}
